import { defineStore } from 'pinia'
import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import router, { staticRoutes } from '../router'
import { HOME } from '../constant'
import { setTitle } from '../hooks/TitleConfig'
import { useTabBarStore } from '../store/layout/tabBar'

/**
 * router meta
 * @param public 免登录
 * @param title  显示标题
 * @param keepAlive  缓存
 */
export const useRouterStore = defineStore('userRouter', {
  state: () => {
    const layoutRoutes = new Map() as Map<string, RouteRecordRaw>
    const publicRoutes = new Map() as Map<string, RouteRecordRaw>
    staticRoutes.forEach((r) => {
      publicRoutes.set(r.path, r)
    })
    // 添加动态路由和公共路由
    return {
      afterLoginHandler: async () => {},
      _blockReturn: false,
      _blockReturnHandler: () => {},
      layoutRoutes,
      publicRoutes,
      lastRoute: {} as RouteLocationNormalized,
      currentRoute: {} as RouteLocationNormalized,
      keepAliveList: [] as Array<string>
    }
  },
  actions: {
    blockReturn(block: boolean, handler?: () => void) {
      if (block && handler) {
        this._blockReturnHandler = handler
      } else {
        this._blockReturnHandler = () => {}
      }
      this._blockReturn = block
    },
    blockReturnHandler() {
      this._blockReturnHandler()
    },
    setLastRoute(route: RouteLocationNormalized) {
      this.lastRoute = route
    },
    setCurrentRoute(route: RouteLocationNormalized) {
      this.currentRoute = route
      setTitle(route.meta.title as string)
      const tabBarStore = useTabBarStore()
      if (!route.meta.subPage) {
        tabBarStore.setCurrentTab(route.path)
      }
    },
    async setAfterLoginHandler(fun: () => Promise<any>) {
      this.afterLoginHandler = fun
    },
    // 建议在main.ts中的 app.mount 语句之前调用该函数
    addLayoutRoutes(routes: Array<RouteRecordRaw>) {
      routes.forEach((r) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        r.name = r.component().then((module: any) => {
          r.name = module.default.name || module.default.__name
          if (r.meta?.keepAlive) {
            this.keepAliveList.push(r.name as string)
          }
        })
        if (!this.layoutRoutes.has(r.path)) {
          this.layoutRoutes.set(r.path, r)
          router.addRoute(HOME, r)
        }
      })
    },
    addPublicRoutes(routes: Array<RouteRecordRaw>) {
      routes.forEach((r) => {
        if (!this.publicRoutes.has(r.path)) {
          this.publicRoutes.set(r.path, r)
          router.addRoute(r)
        }
      })
    }
  },
  getters: {
    getAfterLoginHandler: (state) => state.afterLoginHandler,
    getLayoutRoutes: (state) => state.layoutRoutes,
    getPublicRoutes: (state) => state.publicRoutes,
    getLastRoute: (state) => state.lastRoute,
    getCurrentRoute: (state) => state.currentRoute,
    getKeepAliveList: (state) => state.keepAliveList,
    isBlockReturn: (state) => state._blockReturn
  }
})
